#include "mutexsocketlist.h"

void initialize_MutexSocketList(MutexSocketList *mutexSocketList,
                                const int maxSocket)
{
    initialize_List(&(mutexSocketList->fileSocket), create_IntList,
                    destroy_IntList, NULL, NULL);
    mutexSocketList->maxSocket = maxSocket;
    mutexSocketList->nbSocketConnect = 0;
    mutexSocketList->continu = 1;
    pthread_mutex_init(&(mutexSocketList->mutexAcces), NULL);
    pthread_cond_init(&(mutexSocketList->condVide), NULL);
}

void testament_MutexSocketList(MutexSocketList *mutexSocketList)
{
    testament_List(&(mutexSocketList->fileSocket));
    pthread_mutex_destroy(&(mutexSocketList->mutexAcces));
    pthread_cond_destroy(&(mutexSocketList->condVide));
}

MutexSocketListReturn insert_MutexSocketList(MutexSocketList *mutexSocketList,
                                             const Element element)
{
    pthread_mutex_lock(&(mutexSocketList->mutexAcces));
    
    if(insertLast_List(&(mutexSocketList->fileSocket), element) == LIST_ERR)
      {
	pthread_mutex_unlock(&(mutexSocketList->mutexAcces));
	return MUTEXSOCKETLIST_ERR;
      }
    pthread_cond_signal(&(mutexSocketList->condVide));

    pthread_mutex_unlock(&(mutexSocketList->mutexAcces));

    return MUTEXSOCKETLIST_SUCCESS;
}

int getFirst_MutexSocketList(MutexSocketList *mutexSocketList)
{
    int *s;
    int res;
    if(mutexSocketList->continu == 0)
      return -1;
    pthread_mutex_lock(&(mutexSocketList->mutexAcces));

    while(getSize_List(&(mutexSocketList->fileSocket))==0)
    {
        pthread_cond_wait(&(mutexSocketList->condVide),
                          &(mutexSocketList->mutexAcces));
	if(mutexSocketList->continu == 0)
	  {
	    pthread_mutex_unlock(&(mutexSocketList->mutexAcces));
	    return -1;
	  }
    }

    s=getDataFirst_List(&(mutexSocketList->fileSocket));
    res=(*s);
    
    destroyFirst_List(&(mutexSocketList->fileSocket));

    pthread_mutex_unlock(&(mutexSocketList->mutexAcces));

    return res;

}

void notifyEnd_MutexSocketList(MutexSocketList *mutexSocketList)
{
  mutexSocketList->continu = 0;
  pthread_cond_broadcast(&(mutexSocketList->condVide));
}

void addConnection_MutexSocketList(MutexSocketList *mutexSocketList)
{
    pthread_mutex_lock(&(mutexSocketList->mutexAcces));
    mutexSocketList->nbSocketConnect ++;
    pthread_mutex_unlock(&(mutexSocketList->mutexAcces));
}

void subtractConnection_MutexSocketList(MutexSocketList *mutexSocketList)
{
    pthread_mutex_lock(&(mutexSocketList->mutexAcces));
    mutexSocketList->nbSocketConnect --;
    pthread_mutex_unlock(&(mutexSocketList->mutexAcces));
}

int isMaxConnected_MutexSocketList(MutexSocketList *mutexSocketList)
{
  int ret = MUTEXSOCKETLIST_NO;
  pthread_mutex_lock(&(mutexSocketList->mutexAcces));

  if(mutexSocketList->nbSocketConnect >= mutexSocketList->maxSocket)
    ret = MUTEXSOCKETLIST_YES;
  pthread_mutex_unlock(&(mutexSocketList->mutexAcces));
  return ret;
}
